package com.fyzs.mp3recorder

import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.HandlerThread
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import java.io.File

class MediaRecordFragment : Fragment() {

    var mediaRecorder : MediaRecorder?=null

    val workThread = HandlerThread("recorder").apply { start() }

    val workHandler = Handler(workThread.looper)


    lateinit var mStateTv:TextView
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_media_record, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mStateTv = view.findViewById(R.id.record_state)


        view.findViewById<Button>(R.id.start_btn).setOnClickListener { start() }
        view.findViewById<Button>(R.id.stop_btn).setOnClickListener { stop() }
    }


    fun start(){
//        val cacheDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_MUSIC)
        val cacheDir = requireContext().cacheDir

        val fileName ="${System.currentTimeMillis()}.wav"

        val targetFile = File(cacheDir,fileName)
        if (targetFile.exists().not()) {
            targetFile.createNewFile()
        }
        mediaRecorder = MediaRecorder().apply {
            setAudioSource(MediaRecorder.AudioSource.MIC)
            setOutputFormat(MediaRecorder.OutputFormat.AMR_NB)

            setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
            setAudioChannels(2)
            setAudioSamplingRate(44100)
            setOutputFile(targetFile.absolutePath)
            prepare()
            start()
        }

    }
    fun stop(){
        mediaRecorder?.stop()
        mediaRecorder?.reset()
        mediaRecorder?.release()
    }
}